package com.mtiiot.fsmanage.controller;


import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.ReportingEngine;
import com.mtiiot.fscore.bean.MetadataInfo;
import com.mtiiot.fscore.inter1.FastdfsService1;
import com.mtiiot.fscore.inter1.ReportService1;
import com.mtiiot.fscore.utils.FileUtil;
import com.mtiiot.fscore.utils.StringUtil;
import com.mtiiot.fscore.utils.TemplateExtType;
import com.mtiiot.fsmanage.server.ReportServer;
import com.mtiiot.fsmanage.utils.FsViewConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * Created by Administrator on 16-8-18.
 */


@Controller
public class ReportController {
    @Autowired
    private FsViewConfig fsViewConfig;
    @Autowired
    private ReportServer reportServer;
    @Autowired
    private FastdfsService1 fastdfsService1;
    //fs 的报告单服务
    @Autowired
    private ReportService1 reportService1;

    private static InputStream license;
    static{
        try {
            license = ReportController.class.getResourceAsStream("/license.xml");
            License aposeLic = new License();
            aposeLic.setLicense(license);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 查询ftp数据
     * @return
     */
    @RequestMapping(value="/report/reportQuery.action",produces="application/json;charset=UTF-8")
    @ResponseBody
    public Object reportQuery(String sysName,String l1Name,String l2Name,String l3Name,String times,String queryKeyWord,int count,String sort,String reportType)throws Exception{
        Object obj = reportServer.reportQuery(sysName ,l1Name ,l2Name ,l3Name ,times ,queryKeyWord ,count ,sort,reportType);
        ObjectMapper mapper = new ObjectMapper();
        String jsonStr = mapper.writeValueAsString(obj);
        return jsonStr;
    }

    /**
     * 查询ftp数据
     */
    @RequestMapping(value="/report/reportStatistics.action",produces="application/json;charset=UTF-8")
    @ResponseBody
    public Object reportStatistics(String sysName,String l1Name,String l2Name,String l3Name,String times,String reportType) throws Exception {
        Object obj=reportServer.reportStatistics(sysName, l1Name, l2Name, l3Name, times,reportType);
        ObjectMapper mapper = new ObjectMapper();
        String jsonStr=mapper.writeValueAsString(obj);
        System.out.println(jsonStr);
        return jsonStr;
    }


    @RequestMapping(value = "/report/reportDownload.action")
    @ResponseBody
    public void reportDownload(String dfsId,String ext,String type,HttpServletResponse response) {
        InputStream ins=null;
        ServletOutputStream out=null;
		try {
			byte[] data=fastdfsService1.getFile(new MetadataInfo(fsViewConfig.getFsviewSysId()),dfsId).getFile();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            String fileName = sdf.format(new Date())+"."+ext;
            if("download".equals(type)){
                //下载
                response.setContentType("application/x-download");
                response.addHeader("Content-Disposition","attachment;filename=" + fileName);
            }else{
                //预览
                response.setContentType("application/pdf");
                if("doc".equals(ext)||"docx".equals(ext)){
                    Document doc=new Document(new ByteArrayInputStream(data));
                    ByteArrayOutputStream baos=new ByteArrayOutputStream();
                    doc.save(baos,40);//生成报告单
                    data=baos.toByteArray();
                }
            }
            out = response.getOutputStream();
            ins = new ByteArrayInputStream(data);
            IOUtils.copy(ins, out);
            out.flush();
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            if(ins!=null){
                try {
                    ins.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(out!=null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @RequestMapping(value = "/report/uploadTemplate.action")
    @ResponseBody
    public Object uploadTemplate(@RequestParam(value = "templateFile")MultipartFile templateFile,String sysId,String templateAlias,String templateComment) {
        Map<String, Object> resMap = new HashMap<String, Object>();
        String jsonStr=null;
        try {
            // 文件原名称
            String originFileName = templateFile.getOriginalFilename();
            String ext=originFileName.split("\\.")[1];
            TemplateExtType tet=null;
            if("doc".equals(ext)){
                tet=TemplateExtType.EXT_DOC;
            }else{
                tet=TemplateExtType.EXT_DOCX;
            }
            byte[] bytes=FileUtil.getBytesByInputStream(templateFile.getInputStream());
            String dfsId=reportService1.uploadTemplate(new MetadataInfo(sysId),templateAlias, tet,templateComment,bytes);
            if(!StringUtil.isEmpty(dfsId)){
                resMap.put("status","success");
            }
            ObjectMapper mapper = new ObjectMapper();
            jsonStr=mapper.writeValueAsString(resMap);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonStr;
    }
}
